<template>
  <div class="starrocks-table-growth-form">
    <el-form label-width="140px" :model="localValue">
      <!-- StarRocks集群配置 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><Histogram /></el-icon>
          <span>StarRocks集群配置</span>
        </div>
        <el-form-item label="选择StarRocks集群" required>
          <ServiceConfigSelector
            v-model="clusterIdSelector"
            service-type="starrocks"
            placeholder="请选择StarRocks集群"
          />
        </el-form-item>
      </section>

      <!-- 表选择 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><List /></el-icon>
          <span>表选择</span>
        </div>
        <el-form-item label="选择方式">
          <el-radio-group v-model="localValue.table_selection.selection_type" @change="handleSelectionTypeChange">
            <el-radio label="specific_tables">指定表</el-radio>
            <el-radio label="all_in_databases">全库表</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数据库" v-if="localValue.table_selection.selection_type === 'all_in_databases'">
          <el-select
            v-model="localValue.table_selection.database_names"
            multiple
            filterable
            placeholder="请选择数据库"
            :loading="databasesLoading"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
            @visible-change="handleDatabasesVisibleChange"
            @change="emitParams"
          >
            <el-option
              v-for="db in databaseOptions"
              :key="db"
              :label="db"
              :value="db"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表名列表" v-if="localValue.table_selection.selection_type === 'specific_tables'">
          <el-select
            v-model="localValue.table_selection.table_names"
            multiple
            filterable
            allow-create
            placeholder="请选择表（可输入后回车添加）"
            :loading="tablesLoading"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
            @visible-change="handleTablesVisibleChange"
            @change="emitParams"
          >
            <el-option
              v-for="table in tableOptions"
              :key="table"
              :label="table"
              :value="table"
            />
          </el-select>
        </el-form-item>
      </section>

      <!-- 统计配置 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><TrendCharts /></el-icon>
          <span>统计配置</span>
        </div>
        <el-form-item label="统计类型">
          <el-radio-group v-model="localValue.statistics_config.stat_type" @change="emitParams">
            <el-radio label="no_growth">无增长表</el-radio>
            <el-radio label="top_n">增量TOP N</el-radio>
            <el-radio label="full_report">全量报表</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="localValue.statistics_config.stat_type === 'top_n'"
          label="TOP N数量"
        >
          <el-input-number
            v-model="localValue.statistics_config.top_n"
            :min="1"
            :max="100"
            @change="emitParams"
          />
        </el-form-item>
        <el-form-item label="排序字段">
          <el-radio-group v-model="localValue.statistics_config.sort_by" @change="emitParams">
            <el-radio label="row_increment">按行数增量</el-radio>
            <el-radio label="size_increment">按数据大小增量</el-radio>
          </el-radio-group>
        </el-form-item>
      </section>

      <!-- 时间维度 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><Clock /></el-icon>
          <span>时间维度</span>
        </div>
        <el-form-item label="时间类型">
          <el-radio-group v-model="localValue.time_dimension.dimension_type" @change="emitParams">
            <el-radio label="last_hour">最近1小时</el-radio>
            <el-radio label="last_day">最近1天</el-radio>
            <el-radio label="last_week">最近7天</el-radio>
            <el-radio label="last_month">最近30天</el-radio>
            <el-radio label="custom">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="localValue.time_dimension.dimension_type === 'custom'" style="margin-left: 140px;">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="localValue.time_dimension.custom_start"
              type="datetime"
              placeholder="选择开始时间"
              @change="emitParams"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="localValue.time_dimension.custom_end"
              type="datetime"
              placeholder="选择结束时间"
              @change="emitParams"
            />
          </el-form-item>
        </div>
      </section>

      <!-- 显示字段 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><Filter /></el-icon>
          <span>显示字段</span>
        </div>
        <el-checkbox-group v-model="localValue.display_fields" @change="emitParams">
          <el-checkbox
            v-for="field in displayFieldOptions"
            :key="field.value"
            :label="field.value"
          >
            {{ field.label }}
          </el-checkbox>
        </el-checkbox-group>
      </section>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, watch, ref } from 'vue'
import { Filter, List, Clock, Histogram, TrendCharts } from '@element-plus/icons-vue'
import ServiceConfigSelector from '../../shared/ServiceConfigSelector.vue'
import api from '@/utils/api'

interface TableGrowthParams {
  starrocks_cluster_config: { cluster_id: number | null }
  table_selection: {
    selection_type: 'specific_tables' | 'all_in_databases'
    database_names: string[]
    table_names: string[]
  }
  statistics_config: {
    stat_type: 'no_growth' | 'top_n' | 'full_report'
    top_n: number
    sort_by: 'row_increment' | 'size_increment'
  }
  time_dimension: {
    dimension_type: 'last_hour' | 'last_day' | 'last_week' | 'last_month' | 'custom'
    custom_start?: string
    custom_end?: string
  }
  display_fields: string[]
}

const props = defineProps<{
  modelValue: TableGrowthParams | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: TableGrowthParams): void
}>()

const defaultValue = (): TableGrowthParams => ({
  starrocks_cluster_config: { cluster_id: null },
  table_selection: {
    selection_type: 'specific_tables',
    database_names: [],
    table_names: []
  },
  statistics_config: {
    stat_type: 'full_report',
    top_n: 10,
    sort_by: 'row_increment'
  },
  time_dimension: {
    dimension_type: 'last_day'
  },
  display_fields: ['database', 'table', 'current_rows', 'row_increment', 'growth_status']
})

const localValue = reactive<TableGrowthParams>({
  ...defaultValue(),
  ...(props.modelValue || {})
})

// Computed属性用于ServiceConfigSelector
const clusterIdSelector = computed({
  get: () => localValue.starrocks_cluster_config.cluster_id ?? undefined,
  set: (value: number | undefined) => {
    localValue.starrocks_cluster_config.cluster_id = value ?? null
    emitParams()
  }
})

// 数据库选项
const databaseOptions = ref<string[]>([])
const databasesLoading = ref(false)

// 表选项
const tableOptions = ref<string[]>([])
const tablesLoading = ref(false)

// 当集群选择变化时，加载数据库列表
watch(
  () => localValue.starrocks_cluster_config.cluster_id,
  async (newClusterId) => {
    if (newClusterId) {
      await fetchDatabases(newClusterId)
    } else {
      databaseOptions.value = []
      tableOptions.value = []
    }
  }
)

const fetchDatabases = async (clusterId: number) => {
  try {
    databasesLoading.value = true
    const response = await api.get('/reports/starrocks-databases', {
      params: { config_id: clusterId }
    })
    if (response.data.success) {
      databaseOptions.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取数据库列表失败', error)
  } finally {
    databasesLoading.value = false
  }
}

const fetchTables = async (clusterId: number) => {
  try {
    tablesLoading.value = true
    const response = await api.get('/reports/starrocks-tables', {
      params: { config_id: clusterId }
    })
    if (response.data.success) {
      // 提取表名（格式为 database.table_name）
      const tables = response.data.data || []
      tableOptions.value = tables.map((t: any) => `${t.database_name}.${t.table_name}`)
    }
  } catch (error) {
    console.error('获取表列表失败', error)
  } finally {
    tablesLoading.value = false
  }
}

const handleDatabasesVisibleChange = async (visible: boolean) => {
  if (visible && databaseOptions.value.length === 0 && localValue.starrocks_cluster_config.cluster_id) {
    await fetchDatabases(localValue.starrocks_cluster_config.cluster_id)
  }
}

const handleTablesVisibleChange = async (visible: boolean) => {
  if (visible && tableOptions.value.length === 0 && localValue.starrocks_cluster_config.cluster_id) {
    await fetchTables(localValue.starrocks_cluster_config.cluster_id)
  }
}

const handleSelectionTypeChange = () => {
  // 切换选择方式时清空另一个
  if (localValue.table_selection.selection_type === 'specific_tables') {
    localValue.table_selection.database_names = []
  } else {
    localValue.table_selection.table_names = []
  }
  emitParams()
}

const displayFieldOptions = [
  { value: 'database', label: '数据库名' },
  { value: 'table', label: '表名' },
  { value: 'current_rows', label: '当前行数' },
  { value: 'current_size', label: '当前数据大小' },
  { value: 'row_increment', label: '行数增量' },
  { value: 'size_increment', label: '数据大小增量' },
  { value: 'growth_status', label: '增长状态' },
  { value: 'last_stat_time', label: '最后统计时间' }
]

const emitParams = () => {
  emit('update:modelValue', JSON.parse(JSON.stringify(localValue)))
}

watch(() => props.modelValue, (val) => {
  if (val) {
    Object.assign(localValue, defaultValue(), val)
  }
}, { deep: true })
</script>

<style scoped>
.form-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}
</style>
